{% extends "base.html" %}

{% block title %}座位预约状态管理{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><i class="fas fa-cog"></i> 座位预约状态管理</h2>
                <a href="{{ url_for('library') }}" class="btn btn-outline-primary">
                    <i class="fas fa-arrow-left"></i> 返回座位表
                </a>
            </div>
        </div>
    </div>

    <!-- 座位信息卡片 -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-chair"></i> 座位信息
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <p><strong>座位号：</strong><span id="seatNumber">{{ seat.seat_number }}</span></p>
                            <p><strong>楼层：</strong>{{ seat.floor }}楼</p>
                        </div>
                        <div class="col-md-6">
                            <p><strong>当前状态：</strong><span id="currentStatus" class="badge badge-info" style="color: #ffffff; font-weight: 600; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none; box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);">{{ seat.status }}</span></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 时间段选择 -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-clock"></i> 时间段选择
                    </h5>
                </div>
                <div class="card-body">
                    <form id="timeSelectionForm">
                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="queryDate">查询日期</label>
                                    <input type="date" class="form-control" id="queryDate" required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="queryStartTime">开始时间</label>
                                    <select class="form-control" id="queryStartTime" required>
                                        <option value="">请选择开始时间</option>
                                        <option value="08:00">08:00</option>
                                        <option value="09:00">09:00</option>
                                        <option value="10:00">10:00</option>
                                        <option value="11:00">11:00</option>
                                        <option value="12:00">12:00</option>
                                        <option value="13:00">13:00</option>
                                        <option value="14:00">14:00</option>
                                        <option value="15:00">15:00</option>
                                        <option value="16:00">16:00</option>
                                        <option value="17:00">17:00</option>
                                        <option value="18:00">18:00</option>
                                        <option value="19:00">19:00</option>
                                        <option value="20:00">20:00</option>
                                        <option value="21:00">21:00</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="queryEndTime">结束时间</label>
                                    <select class="form-control" id="queryEndTime" required>
                                        <option value="">请选择结束时间</option>
                                        <option value="09:00">09:00</option>
                                        <option value="10:00">10:00</option>
                                        <option value="11:00">11:00</option>
                                        <option value="12:00">12:00</option>
                                        <option value="13:00">13:00</option>
                                        <option value="14:00">14:00</option>
                                        <option value="15:00">15:00</option>
                                        <option value="16:00">16:00</option>
                                        <option value="17:00">17:00</option>
                                        <option value="18:00">18:00</option>
                                        <option value="19:00">19:00</option>
                                        <option value="20:00">20:00</option>
                                        <option value="21:00">21:00</option>
                                        <option value="22:00">22:00</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12">
                                <button type="button" class="btn btn-primary" onclick="queryReservations()">
                                    <i class="fas fa-search"></i> 查询预约状态
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- 预约记录列表 -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-list"></i> 预约记录
                    </h5>
                </div>
                <div class="card-body">
                    <div id="reservationsList">
                        <p class="text-muted text-center">请选择时间段查询预约记录</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 状态修改操作 -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-edit"></i> 管理操作
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4">
                            <button class="btn btn-success btn-block w-100" onclick="createReservation()">
                                <i class="fas fa-plus"></i> 创建新预约
                            </button>
                        </div>
                        <div class="col-md-4">
                            <button class="btn btn-warning btn-block w-100" onclick="showStatusChangeModal()">
                                <i class="fas fa-exchange-alt"></i> 修改预约状态
                            </button>
                        </div>
                        <div class="col-md-4">
                            <a href="{{ url_for('admin_face_recognition_page') }}" class="btn btn-danger btn-block w-100" target="_blank">
                                <i class="fas fa-camera"></i> 人脸识别入馆
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 创建预约模态框 -->
<div class="modal fade" id="createReservationModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">创建新预约</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="createReservationForm">
                    <div class="form-group">
                        <label for="studentId">学生ID</label>
                        <input type="text" class="form-control" id="studentId" required>
                    </div>
                    <div class="form-group">
                        <label for="reservationDate">预约日期</label>
                        <input type="date" class="form-control" id="reservationDate" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="startTime">开始时间</label>
                                <select class="form-control" id="startTime" required>
                                    <option value="">请选择</option>
                                    <option value="08:00">08:00</option>
                                    <option value="09:00">09:00</option>
                                    <option value="10:00">10:00</option>
                                    <option value="11:00">11:00</option>
                                    <option value="12:00">12:00</option>
                                    <option value="13:00">13:00</option>
                                    <option value="14:00">14:00</option>
                                    <option value="15:00">15:00</option>
                                    <option value="16:00">16:00</option>
                                    <option value="17:00">17:00</option>
                                    <option value="18:00">18:00</option>
                                    <option value="19:00">19:00</option>
                                    <option value="20:00">20:00</option>
                                    <option value="21:00">21:00</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="endTime">结束时间</label>
                                <select class="form-control" id="endTime" required>
                                    <option value="">请选择</option>
                                    <option value="09:00">09:00</option>
                                    <option value="10:00">10:00</option>
                                    <option value="11:00">11:00</option>
                                    <option value="12:00">12:00</option>
                                    <option value="13:00">13:00</option>
                                    <option value="14:00">14:00</option>
                                    <option value="15:00">15:00</option>
                                    <option value="16:00">16:00</option>
                                    <option value="17:00">17:00</option>
                                    <option value="18:00">18:00</option>
                                    <option value="19:00">19:00</option>
                                    <option value="20:00">20:00</option>
                                    <option value="21:00">21:00</option>
                                    <option value="22:00">22:00</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitCreateReservation()">创建预约</button>
            </div>
        </div>
    </div>
</div>

<!-- 状态修改模态框 -->
<div class="modal fade" id="statusChangeModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">修改预约状态</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div id="statusChangeContent">
                    <p class="text-muted">请先查询预约记录，然后选择要修改的预约</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>

<style>
.badge {
    font-size: 0.9em;
}

.card {
    border: none;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    border-radius: 15px;
    margin-bottom: 20px;
}

.card-header {
    background: linear-gradient(45deg, #f8f9fa, #e9ecef);
    border-bottom: 1px solid #dee2e6;
    border-radius: 15px 15px 0 0 !important;
}

.reservation-item {
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 10px;
    background: #f8f9fa;
}

.reservation-item.active {
    border-color: #007bff;
    background: #e3f2fd;
}

.status-badge {
    padding: 5px 10px;
    border-radius: 15px;
    font-size: 0.8em;
}

.status-reserved {
    background: #fff3cd;
    color: #856404;
}

.status-using {
    background: #d1ecf1;
    color: #0c5460;
}

.status-available {
    background: #d4edda;
    color: #155724;
}
</style>

<script>
let currentSeatId = {{ seat.id }};
let selectedReservationId = null;

// 页面加载时设置默认日期
document.addEventListener('DOMContentLoaded', function() {
    const today = new Date().toISOString().split('T')[0];
    document.getElementById('queryDate').value = today;
    document.getElementById('reservationDate').value = today;
    
    // 设置最小日期为今天
    document.getElementById('queryDate').min = today;
    document.getElementById('reservationDate').min = today;
});

// 查询预约状态
function queryReservations() {
    const date = document.getElementById('queryDate').value;
    const startTime = document.getElementById('queryStartTime').value;
    const endTime = document.getElementById('queryEndTime').value;
    
    if (!date || !startTime || !endTime) {
        alert('请填写完整的查询条件');
        return;
    }
    
    if (startTime >= endTime) {
        alert('结束时间必须晚于开始时间');
        return;
    }
    
    fetch('/query_seat_reservations', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            seat_id: currentSeatId,
            date: date,
            start_time: startTime,
            end_time: endTime
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            displayReservations(data.reservations);
        } else {
            alert(data.message || '查询失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('查询失败，请重试');
    });
}

// 显示预约记录
function displayReservations(reservations) {
    const container = document.getElementById('reservationsList');
    
    if (reservations.length === 0) {
        container.innerHTML = '<p class="text-muted text-center">该时间段内没有预约记录</p>';
        return;
    }
    
    let html = '';
    reservations.forEach(reservation => {
        const statusClass = reservation.status === '已预约' ? 'status-reserved' : 
                           reservation.status === '使用中' ? 'status-using' : 'status-available';
        
        html += `
            <div class="reservation-item" onclick="selectReservation(${reservation.id})" data-id="${reservation.id}">
                <div class="row">
                    <div class="col-md-3">
                        <strong>学生：</strong>${reservation.student_name}
                    </div>
                    <div class="col-md-3">
                        <strong>时间：</strong>${reservation.start_time_slot} - ${reservation.end_time_slot}
                    </div>
                    <div class="col-md-3">
                        <strong>日期：</strong>${reservation.reservation_date}
                    </div>
                    <div class="col-md-3">
                        <span class="status-badge ${statusClass}">${reservation.status}</span>
                    </div>
                </div>
            </div>
        `;
    });
    
    container.innerHTML = html;
}

// 选择预约记录
function selectReservation(reservationId) {
    // 移除之前的选中状态
    document.querySelectorAll('.reservation-item').forEach(item => {
        item.classList.remove('active');
    });
    
    // 添加选中状态
    document.querySelector(`[data-id="${reservationId}"]`).classList.add('active');
    selectedReservationId = reservationId;
}

// 创建预约
function createReservation() {
    $('#createReservationModal').modal('show');
}

// 提交创建预约
function submitCreateReservation() {
    const studentId = document.getElementById('studentId').value;
    const date = document.getElementById('reservationDate').value;
    const startTime = document.getElementById('startTime').value;
    const endTime = document.getElementById('endTime').value;
    
    if (!studentId || !date || !startTime || !endTime) {
        alert('请填写完整的预约信息');
        return;
    }
    
    if (startTime >= endTime) {
        alert('结束时间必须晚于开始时间');
        return;
    }
    
    fetch('/admin_create_reservation', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            student_id: studentId,
            seat_id: currentSeatId,
            date: date,
            start_time: startTime,
            end_time: endTime
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            $('#createReservationModal').modal('hide');
            alert('预约创建成功');
            // 清空表单
            document.getElementById('createReservationForm').reset();
            // 重新查询
            queryReservations();
        } else {
            alert(data.message || '创建失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('创建失败，请重试');
    });
}

// 显示状态修改模态框
function showStatusChangeModal() {
    if (!selectedReservationId) {
        alert('请先选择一个预约记录');
        return;
    }
    
    const content = `
        <div class="form-group">
            <label>选择新状态：</label>
            <select class="form-control" id="newStatus">
                <option value="已预约">已预约</option>
                <option value="使用中">使用中</option>
            </select>
        </div>
        <div class="text-center">
            <button class="btn btn-primary" onclick="changeReservationStatus()">确认修改</button>
            <button class="btn btn-danger ml-2" onclick="deleteReservation()">删除预约</button>
        </div>
    `;
    
    document.getElementById('statusChangeContent').innerHTML = content;
    $('#statusChangeModal').modal('show');
}

// 修改预约状态
function changeReservationStatus() {
    const newStatus = document.getElementById('newStatus').value;
    
    fetch('/admin_change_reservation_status', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            reservation_id: selectedReservationId,
            new_status: newStatus
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            $('#statusChangeModal').modal('hide');
            alert('状态修改成功');
            queryReservations();
        } else {
            alert(data.message || '修改失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('修改失败，请重试');
    });
}

// 删除预约
function deleteReservation() {
    if (confirm('确定要删除这个预约吗？')) {
        fetch('/admin_delete_reservation', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                reservation_id: selectedReservationId
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                $('#statusChangeModal').modal('hide');
                alert('预约删除成功');
                queryReservations();
                selectedReservationId = null;
            } else {
                alert(data.message || '删除失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('删除失败，请重试');
        });
    }
}

// 时间选择联动
document.getElementById('queryStartTime').addEventListener('change', function() {
    const startTime = this.value;
    const endTimeSelect = document.getElementById('queryEndTime');
    const endOptions = endTimeSelect.options;
    
    for (let i = 0; i < endOptions.length; i++) {
        endOptions[i].disabled = false;
    }
    
    if (startTime) {
        for (let i = 0; i < endOptions.length; i++) {
            if (endOptions[i].value && endOptions[i].value <= startTime) {
                endOptions[i].disabled = true;
            }
        }
        endTimeSelect.value = '';
    }
});

document.getElementById('startTime').addEventListener('change', function() {
    const startTime = this.value;
    const endTimeSelect = document.getElementById('endTime');
    const endOptions = endTimeSelect.options;
    
    for (let i = 0; i < endOptions.length; i++) {
        endOptions[i].disabled = false;
    }
    
    if (startTime) {
        for (let i = 0; i < endOptions.length; i++) {
            if (endOptions[i].value && endOptions[i].value <= startTime) {
                endOptions[i].disabled = true;
            }
        }
        endTimeSelect.value = '';
    }
});
</script>
{% endblock %}